/**
 * @桓桓
 * 转让
 */

import React, {Component} from 'react'
import {
    Text,
    View,
    Image,
    TextInput,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
    StatusBar
} from 'react-native'
import NetRequest from '../../utils/utilsRequest'
import ServicesApi from '../../constants/ServicesApi'
import GlobalStyles from '../../constants/GlobalStyles'
import NavigationBar from '../../components/common/NavigationBar'
import AlertManager from '../../components/common/AlertManager'
import UtilsView from '../../utils/utilsView'
import { toastShort, consoleLog } from '../../utils/utilsToast'

export default class zhuanrang extends Component {

    constructor(props) {
        super(props);
        const { params } = this.props.navigation.state;
        this.state =  {
            id: params.fund_id, // 基金id
            dataSource: [],
            transfering_money: '',

            money: '',
            money_text: '',
            price: '',
            price_text: '',
            total_price: '',
            total_price_text: '',
            is_many: 1,
        }
        // this.netRequest = new NetRequest();
    }

    async componentWillMount(){
        try {
            await this.getDataSource();
        } catch (error) {
            console.log(error);
        }
    }

    getDataSource = () => {
        let url = ServicesApi.transfer_transfer_detail;
        let data = {
            id: this.state.id,
        }
        Services.post(url, data, true)
            .then( result => {
                if (result && result.code == StatusCode.SUCCESS_CODE) {
                    this.setState({
                        dataSource: result.data.detail,
                        transfering_money: result.data.transfering_money,
                    })
                }else{
                    toastShort(result.msg);
                }
            })
            .catch( error => {
                toastShort('服务器请求失败，请稍后重试！');
            })
    }

    onBack = () => {
        this.props.navigation.goBack();
    }

    onPushNavigator = (compent, data) => {
        const { navigate } = this.props.navigation;
        navigate( compent , {
            id: data.data.id,// 请求回来的id
        })
    } 

    onPressSubmit = () => {
        const params = {
            title: '',
            detail: '您确认申请该份额转让吗？',
            actions: [
                { title: '取消', titleStyle: {  }, actionStyle: {  }, onPress: () => {  } },
                { title: '确定', onPress: () => this.onSubmit() }
            ]
        }
        AlertManager.show(params)
    }

    onSubmit = () => {
        const { id, money, price, dataSource, is_many } = this.state;
        let url = ServicesApi.transfer_save_transfer;
        let data = {
            fund_id: id,
            money: money,
            price: price,
            is_many: is_many,
            datum_rate: dataSource.datum_rate,
        }
        Services.post(url, data)
        .then( result => {
            if (result && result.code == StatusCode.SUCCESS_CODE) {
                // toastShort(result.msg);
                this.onPushNavigator('ZhuanrangContract', result)
                this.getDataSource();
            }else{
                toastShort(result.msg);
            }  
        })
        .catch( error => {
            toastShort('服务器请求失败，请稍后重试！');
        })
    }

    calculation = () => { // 计算接口
        const { id, money } = this.state;
        let url = ServicesApi.fund_get_money_text;
        let data = {
            fund_id: id,
            money: money,
        }
        Services.post(url, data)
            .then( result => {
                if (result && result.code == StatusCode.SUCCESS_CODE) {
                    // toastShort(result.msg);
                    this.setState({money_text: result.data.money_text})
                }else{
                    toastShort(result.msg);
                }
            })
            .catch( error => {
                // toastShort('服务器请求失败，请稍后重试！');
            })

    }

    _calculation = () => { // 计算接口
        const { money, price } = this.state;
        if (money == '' || price == '') {
            return
        } else {
            let _total_price = money * price
            this.setState({total_price: _total_price})
            let url = ServicesApi.fund_get_money_text;
            let data = {
                money: _total_price,
            }
            Services.post(url, data)
                .then( result => {
                    if (result && result.code == StatusCode.SUCCESS_CODE) {
                        // toastShort(result.msg);
                        this.setState({total_price_text: result.data.money_text})
                    }else{
                        toastShort(result.msg);
                    }
                })
                .catch( error => {
                    // toastShort('服务器请求失败，请稍后重试！');
                })
        }
    }

    render(){
        const { id, dataSource, transfering_money, is_many, money, money_text, price, total_price_text } = this.state;
        return (
            <View style={styles.container}>
                <NavigationBar
                    title = {'转让'}
                    style = {styles.navigationBar}
                    titleStyle = {{color: '#333333'}}
                    leftButton = {UtilsView.getLeftBlackButton(() => this.onBack())}
                    rightButton = {UtilsView.getRightKefuBlackButton(() => this.onPushNavigator('Kefu'))}
                />
                <StatusBar
                    animated = {true}
                    hidden = {false}
                    backgroundColor = {'transparent'}
                    translucent = {true}
                    barStyle = {'dark-content'}
                />
                <ScrollView keyboardShouldPersistTaps={'handled'}>
                    <View style={styles.box}>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>基金id</Text>
                            <Text style={styles.lineRight}>{id}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>基金名称</Text>
                            <Text style={styles.lineRight}>{dataSource.fund_id_name}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>可用份额</Text>
                            <Text style={styles.lineRight}>{dataSource.available_amount}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>转让中份额</Text>
                            <Text style={styles.lineRight}>{transfering_money}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>业绩比较基准</Text>
                            <Text style={styles.lineRight}>{dataSource.datum_rate}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>份额确认日</Text>
                            <Text style={styles.lineRight}>{dataSource.confirm_day}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>当前未结算收益</Text>
                            <Text style={styles.lineRight}>{dataSource.income_amount}</Text>
                        </View>
                    </View>

                    <View style={styles.box}>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>转让份额</Text>
                            <TextInput
                                placeholder={'转让总份额' }
                                keyboardType="numeric"
                                onChangeText={(text) => this.setState({money: text}, () => this.calculation(), () => this._calculation())}
                                style={styles.lineInput}
                                underlineColorAndroid={'transparent'}
                            />
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>转让单价</Text>
                            <TextInput
                                placeholder={'每份份额单价' }
                                keyboardType="numeric"
                                onChangeText={(text) => this.setState({price: text}, () => this._calculation())}
                                style={styles.lineInput}
                                underlineColorAndroid={'transparent'}
                            />
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>同意多人共同受让</Text>
                            <View style={styles.redioBox}>
                                <TouchableOpacity style={styles.redioTag} onPress={() => this.setState({is_many: 1})}>
                                    <View style={styles.redio}>
                                        {is_many == 1 && <View style={styles.redioBall}/>}
                                    </View>
                                    <Text style={styles.redioText}>是</Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={styles.redioTag} onPress={() => this.setState({is_many: 2})}>
                                    <View style={styles.redio}>
                                        {is_many == 2 && <View style={styles.redioBall}/>}
                                    </View>
                                    <Text style={styles.redioText}>否</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>

                    <View style={[styles.box, {marginBottom: 0}]}>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>转让份额</Text>
                            <Text style={styles.lineRight}>{money}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>转让份额（大写）</Text>
                            <Text style={styles.lineRight}>{money_text}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>转让单价</Text>
                            <Text style={styles.lineRight}>{price}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>转让总价</Text>
                            <Text style={styles.lineRight}>{money !== '' && price !== '' ? money * price : 0}</Text>
                        </View>
                        <View style={styles.line}>
                            <Text style={styles.lineLeft}>转让总价（大写）</Text>
                            <Text style={styles.lineRight}>{total_price_text}</Text>
                        </View>
                        <TouchableOpacity style={styles.footerBtn} onPress={() => this.onPressSubmit()}>
                            <Text style={styles.footerBtnText}>提交转让申请</Text>
                        </TouchableOpacity>
                    </View>
                </ScrollView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: GlobalStyles.bgColor,
    },
    navigationBar: {
        backgroundColor: '#fff',
        borderBottomColor: '#f2f2f2',
        borderBottomWidth: 1
    },


    box: {
        backgroundColor: '#fff',
        marginBottom: 10,
        paddingHorizontal: 15,
    },
    line: {
        height: 50,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#f2f2f2',
    },
    lineLeft: {
        color: '#666',
        fontSize: 12,
    },
    lineRight: {
        color: '#333',
        fontSize: 12,
    },
    lineInput: {
        width: GlobalStyles.width - 120,
        height: 30,
        paddingVertical: 0,
        paddingHorizontal: 10,
        borderWidth: 1,
        borderColor: '#f2f2f2',
        borderRadius: 5,
        fontSize: 12,
        color: '#333',
    },

    redioBox: {
        flexDirection: 'row',
    },
    redioTag: {
        flexDirection: 'row',
        marginLeft: 15,
    },
    redio: {
        width: 16,
        height: 16,
        borderRadius: 8,
        borderWidth: 1,
        borderColor: '#f2f2f2',
        alignItems: 'center',
        justifyContent: 'center',
    },
    redioBall: {
        width: 10,
        height: 10,
        borderRadius: 5,
        backgroundColor: '#999',
    },
    redioText: {
        color: '#333',
        fontSize: 12,
        marginLeft: 8,
    },

    footerBtn: {
        height: 40,
        backgroundColor: '#b48148',
        borderRadius: 5,
        marginBottom: 10,
        alignItems: 'center',
        justifyContent: 'center',
    },
    footerBtnText: {
        color: '#fff',
        fontSize: 13,
    },
});
